﻿using System;
using System.Linq;
using StyleCop.CSharp;

namespace Jsl.StyleCop.CSharp
{
    /// <summary>
    /// A utility class for determining if a method is a well known or common method.
    /// </summary>
    public static class WellKnownMethodHelper
    {
        #region Public Methods
        /// <summary>
        /// Does the action if this element is a dispose override method.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="action">The action.</param>
        public static void DoIfDisposeOverrideMethod(this CsElement element, Action<Method> action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            var method = element as Method;
            if (IsDisposeOverrideMethod(method))
            {
                action(method);
            }
        }

        /// <summary>
        /// Determines whether the method is the Dispose(bool) method.
        /// </summary>
        /// <param name="method">The method to check. May be <c>null</c>.</param>
        /// <returns><c>true</c> if the method is the Dispose(bool) method.</returns>
        public static bool IsDisposeOverrideMethod(this Method method)
        {
            if (method != null)
            {
                if (method.Name == "method Dispose")
                {
                    if ((method.Parameters.Count == 1) && (method.Parameters[0].Type.Text == "bool"))
                    {
                        if (method.ReturnType.Text == "void")
                        {
                            if (method.AccessModifier == AccessModifierType.Protected)
                            {
                                if (method.ElementTokens.Any(token => token.Text == "override"))
                                {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }

            return false;
        }
        #endregion Public Methods
    }
}